#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -f pthreads-w32-2-8-0-release.tar.gz ] ; then
		wget http://mirrors.kernel.org/sources.redhat.com/pthreads-win32/pthreads-w32-2-8-0-release.tar.gz
	fi
	cd ..
fi

export PATH=$TOP_DIR/cross/bin:$PATH

if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	HOST_FLAG="CROSS=x86_64-w64-mingw32-"
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		HOST_FLAG="CROSS=i686-w64-mingw32-"
	fi
	rm -rf $BIN_DIR/pthreads
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_pthreads
	tar xzf $SRC_DIR/pthreads-w32-2-8-0-release.tar.gz
	mv pthreads-w32-2-8-0-release bd_pthreads
	cd bd_pthreads
	patch -p0 < $TOP_DIR/patch/pthreads-w32.patch
	make -f GNUmakefile $MAKE_OPT $HOST_FLAG GC-inlined

	mkdir -p $BIN_DIR/pthreads/bin
	mkdir -p $BIN_DIR/pthreads/include
	mkdir -p $BIN_DIR/pthreads/lib
	cp *.dll $BIN_DIR/pthreads/bin/
	cp pthread.h sched.h semaphore.h $BIN_DIR/pthreads/include
	cp *.a $BIN_DIR/pthreads/lib/
	cp *.dll $BIN_DIR/pthreads/lib/

	cd ..
	cd ..
fi

